<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <!-- Bootstrap -->
    <link href="../../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="../../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">
    <!-- NProgress -->
    <link href="../../vendors/nprogress/nprogress.css" rel="stylesheet">
    <!-- iCheck -->
    <link href="../../vendors/iCheck/skins/flat/green.css" rel="stylesheet">
    <!-- Custom Theme Style -->
    <link href="../../vendors/custom/custom.min.css" rel="stylesheet">
    <!--Bootstrap-table-->
    <link href="../../vendors/bootstrap-table/dist/bootstrap-table.css" rel="stylesheet">
    <!--kindeditor-->
    <link href="../../vendors/kindeditor/themes/default/default.css" rel="stylesheet">
    <!--自定义样式覆盖-->
    <style>
        body {
            background: #F7F7F7;
        }
    </style>
</head>
<body>
<!--页面表格-->
<div class="row">
    <div class="col-md-12 col-sm-12 col-xs-12">
        <div class="x_panel">
            <div class="x_content">
                <table id="table" class="table table-striped jambo_table bulk_action"></table>
            </div>
        </div>
    </div>
</div>

<!--表格 工具栏-->
<div id="toolbar">
    <button id="add" class="btn btn-danger">
        <i class="fa fa-plus"></i> Add
    </button>

    <span>
        tip：双击修改库存
    </span>
</div>


<!--表格弹出层框架-->
<div class="modal fade" id="tableModel" tabindex="-1" role="dialog" aria-labelledby="tableModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <!--弹出层标题-->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">商品信息</h4>
            </div>
            <div id="alertBlock"></div>

            <!--弹出层主体-->
            <div class="modal-body">
                <form class="form-horizontal" id="form-edit">
                    <div class="form-group">
                        <input type="hidden" id="pid-edit" name="pid"/>
                    </div>
                    <!--第一行：商品名字，商品价格-->
                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品名字：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="pname-static"></p>
                            <input type="text" class="form-control" id="pname-edit" name="pname">
                        </div>
                        <label class="col-sm-2 control-label">商品价格：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="price-static"></p>
                            <input type="text" class="form-control" id="price-edit" name="price">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品卖点：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="ppoint-static"></p>
                            <input type="text" class="form-control" id="ppoint-edit" name="ppoint">
                        </div>
                        <label class="control-label col-sm-2">商品评分：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="pstart-static"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">喜欢人数：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="pheart-static"></p>
                        </div>
                        <label class="control-label col-sm-2">商品分类：</label>
                        <div class="col-sm-3">
                            <p class="form-control-static" id="category-static"></p>
                            <select class="form-control" id="category-edit" name="cid">
                            </select>
                        </div>

                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品展示：</label>
                        <div class="col-sm-10">
                            <input type="button" id="J_selectImage_2" value="批量上传" style="display: none"/>
                            <div id="J_imageView_2" style="height: 153px;width: 153px;border: 1px solid"></div>
                            <input name="imgurl" type="hidden" id="imageurl_2" value="">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品信息：</label>
                        <p class="form-control-static" id="information-static"></p>
                        <div align="center" style="display: none" id="editDiv">
                            <textarea id="information-edit" name="information" cols="100" rows="8"
                                      style="width: 530px; height: 0px; visibility: hidden;"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <!--底部按钮-->
            <div class="modal-footer">
                <button type="button" id="edit_btn" class="btn btn-default">
                    <i class="fa fa-edit"></i> 编辑
                </button>
                <button type="button" id="edit_submit" class="btn btn-primary">
                    <i class="fa fa-floppy-o"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>

<!--删除确认弹出层-->
<div class="modal fade" id="delcfmModel">
    <div class="modal-dialog">
        <div class="modal-content message_align">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">×</span></button>
                <h4 class="modal-title">提示信息</h4>
            </div>
            <div id="alertBlock2"></div>
            <div class="modal-body">
                <p>您确认要删除吗？</p>
            </div>
            <div class="modal-footer">
                <input type="hidden" id="deleteID" name="pid"/>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" onclick="delSubmit()" class="btn btn-success">确定</button>
            </div>
        </div>
    </div>
</div>

<!--添加弹出层-->
<div class="modal fade" id="addModel" tabindex="-1" role="dialog" aria-labelledby="tableModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <!--弹出层标题-->
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="addModalLabel">添加商品</h4>
            </div>
            <div id="alertBlock3"></div>

            <!--弹出层主体-->
            <div class="modal-body">
                <form class="form-horizontal" id="form-add">
                    <div class="form-group">
                        <input type="hidden" id="pid-add" name="pid"/>
                    </div>
                    <!--第一行：商品名字，商品价格-->
                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品名字：</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="pname-add" name="pname">
                        </div>
                        <label class="col-sm-2 control-label">商品价格：</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="price-add" name="price">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品卖点：</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="ppoint-add" name="ppoint">
                        </div>
                        <label class="control-label col-sm-2">商品分类：</label>
                        <div class="col-sm-3">
                            <select class="form-control" id="category-add" name="cid">
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品图片：</label>
                        <div class="col-sm-10">
                            <input type="button" id="J_selectImage" value="批量上传"/>
                            <div id="J_imageView" style="height: 150px;width: 150px;border: 1px solid grey"></div>
                            <input name="imgurl" type="hidden" id="imageurl" value="">
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label col-sm-2">商品信息：</label>
                        <div align="center col-sm-3">
                        <textarea name="information" cols="100" rows="8"
                                  style="width: 450px; height: 200px; visibility: hidden;"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <!--底部按钮-->
            <div class="modal-footer">
                <button type="button" id="add_submit" class="btn btn-primary">
                    <i class="fa fa-floppy-o"></i> 保存
                </button>
            </div>
        </div>
    </div>
</div>

<!--JS插件引入-->

<!--jQuery -->
<script src="../../vendors/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="../../vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- FastClick -->
<script src="../../vendors/fastclick/lib/fastclick.js"></script>
<!-- NProgress -->
<script src="../../vendors/nprogress/nprogress.js"></script>
<!-- iCheck -->
<script src="../../vendors/iCheck/icheck.min.js"></script>
<!--Bootstrap-table-->
<script src="../../vendors/bootstrap-table/dist/bootstrap-table.js"></script>
<script src="../../vendors/bootstrap-table/dist/locale/bootstrap-table-zh-CN.js"></script>
<!-- Custom Theme Scripts -->
<script src="../../vendors/custom/custom.min.js"></script>
<!--myself script-->
<script src="../../vendors/myself/myself.js"></script>
<!--kindeditor-->
<script src="../../vendors/kindeditor/kindeditor-all.js"></script>
<script src="../../vendors/kindeditor/lang/zh-CN.js"></script>

<!--表格相关-->
<script type="text/javascript">

    /**
     * 表格相关
     * @type {jQuery.fn.init|jQuery|HTMLElement}
     */
    const $table = $('#table');
    var itemEditor;
    //页面初始化完毕后执行此方法
    $(function () {
        //创建富文本编辑器
        itemEditor = KindEditor.create("#form-edit [name=information]", {
            resizeType: 1,
            allowImageUpload: true,
            allowFileManager: true,
            // readonlyMode: true,
            minWidth: '500px',
            // uploadJson : '/pic/upload',//服务器端提交的地址
            // filePostName:'uploadFile',//服务器端提交的文件名称
            afterUpload: function (url, data, name) {
                this.sync();//同步将富文本框中的内容同步到textarea
            }
        });
    });

    $(function () {
        var table = new tableInit();
        table.Init();
    });

    var tableInit = function () {
        var table = new Object()
        table.Init = function () {
            $('#table').bootstrapTable({
                url: '/product/getAllProduct',
                toolbar: '#toolbar',
                method: 'get',                      //请求方式（*）
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: false,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                queryParams: queryParams,           //传递参数（*）
                sidePagination: "server",           //分页方式：客户端分页，server服务端分页（*）
                strictSearch: true,
                clickToSelect: true,                //是否启用点击选中行
                height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                // height: getHeight(),
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                showRefresh: true,                      //刷新
                search: true,                       // 搜索
                onDblClickRow: onDblClickRow,
                columns: [{
                    field: 'pid',
                    title: '商品ID',
                    align: 'center'
                }, {
                    field: 'pname',
                    title: '商品名字',
                    align: 'center'
                }, {
                    field: 'price',
                    title: '商品价格',
                    align: 'center',
                    formatter: function (value, row, index) {
                        return '￥' + row.price;
                    }
                }, {
                    field: 'information',
                    title: '商品描述',
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (row.information.length > 10)
                            return row.information.substring(0, 10) + '...';
                        else
                            return row.information;
                    }
                }, {
                    field: 'ppoint',
                    title: '商品卖点',
                    align: 'center'
                }, {
                    field: 'temp',
                    title: '收藏数',
                    align: 'center',
                    visible: false
                }, {
                    field: 'operate',
                    title: '操作',
                    align: 'center',
                    events: operateEvents,
                    formatter: operateFormatter
                }, {
                    field: 'imgurl',
                    title: '图片地址',
                    visible: false,
                }, {
                    field: 'pstart',
                    title: '星级',
                    visible: false,
                }, {
                    field: 'pheart',
                    title: '喜欢数',
                    visible: false,
                }]
            });
        }
        return table;
    }

    function onDblClickRow(row) {
        window.location.href = '/admin/goods/goodDetail.html';
        localStorage.setItem('pid',row.pid);
        localStorage.setItem('cid',row.cid);
    }

    //请求服务数据时所传参数
    function queryParams(params) {
        // return {
        //     pageSize: params.limit, //每一页的数据行数，默认是上面设置的10(pageSize)
        //     pageIndex: params.offset / params.limit + 1, //当前页面,默认是上面设置的1(pageNumber)
        // }
        // console.log(params.search);
        return 'pageSize=' + params.limit + '&' + 'pageIndex=' + (params.offset / params.limit + 1) + '&' + 'search=' + params.search;
    }

    // 表格操作格式化
    function operateFormatter(value, row, index) {
        return [
            '<a class="edit" href="javascript:void(0)" title="Edit">',
            '<i class="fa fa-pencil"></i>',
            '</a>  ',
            '<a class="remove" href="javascript:void(0)" title="Remove">',
            '<i class="fa fa-remove"></i>',
            '</a>'
        ].join('');
    }

    // 表格事件
    var visible_list = [];
    window.operateEvents = {
        'click .edit': function (e, value, row, index) {
            // alert(`You click edit action, row: ${JSON.stringify(row)}`);
            $('#category-edit').html("")
            visible_list = [];
            // 模态层每个编辑框有两个控件，默认显示为静态控件，当点击编辑按钮后，切换到可编辑控件
            $('#pid-edit').val(row.pid);
            $('#pname-static').html(row.pname).show();
            visible_list.push('#pname-static');
            $('#pname-edit').val(row.pname).hide();
            visible_list.push('#pname-edit');
            $('#price-static').html(row.price).show();
            visible_list.push('#price-static');
            $('#price-edit').val(row.price).hide();
            visible_list.push('#price-edit');
            $('#information-static').html(row.information).show();
            visible_list.push('#information-static');
            $('#information-edit').val(row.information).hide();
            visible_list.push('#information-edit');
            $('#ppoint-static').html(row.ppoint).show();
            visible_list.push('#ppoint-static');
            $('#ppoint-edit').val(row.ppoint).hide();
            visible_list.push('#ppoint-edit');
            $('#category-edit').hide();
            visible_list.push('#category-edit');

            //图片控件显示
            if (row.imgurl != "") {
                // 原先有图片，则进行赋值
                $('#J_imageView_2').html('<img style="width: 150px;height: 150px" src="' + row.imgurl + '">');
                $('#imageurl_2').val(row.imgurl);
            } else {
                // 否则为空
                $('#J_imageView_2').html('<img style="width: 150px;height: 150px" src="">');
            }

            $('#edit_btn').show();
            visible_list.push('#edit_btn');
            $('#edit_submit').hide();
            visible_list.push('#edit_submit');
            // 默认编辑框隐藏
            $('#editDiv').hide();
            // 默认图片上传框隐藏
            $('#J_selectImage_2').hide();

            // 静态不可更改的内容
            var star = '';
            for (var num = 0; num < row.pstart; ++num) {
                star += '<i class="fa fa-star"></i>';
            }
            $('#pstart-static').html(star);
            $('#pheart-static').html(row.pheart);

            var nowCategoryName;
            // 分类选项显示
            $.ajax('/categery/getCategeryList', {
                type: 'get',
                success: function (data) {
                    $.each(data.rows, function (i, temp) {
                        if (row.cid == temp.cid) {
                            $('#category-static').html(temp.cname).show();
                            visible_list.push('#category-static');
                            $('#category-edit').append('<option selected="selected" value="' + temp.cid + '">' + temp.cname + '</option>')
                        } else {
                            $('#category-edit').append('<option value="' + temp.cid + '">' + temp.cname + '</option>')
                        }
                    })
                }
            });


            $('#tableModel').modal();
        },
        'click .remove': function (e, value, row, index) {
            $('#deleteID').val(row.pid);
            $('#delcfmModel').modal();
        }
    };

    /**
     * 模态层相关
     */
    // 模态层删除事件
    function delSubmit() {
        $.ajax("/product/deleteProduct", {
            type: 'get',
            data: 'pid=' + $('#deleteID').val(),
            success: function (data) {
                window.location.reload();
                $('#myAlert2').alert();
            },
            error: function (data) {
                $('#alertBlock2').html('<div id="myAlert2" class="alert alert-warning"> <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>警告！</strong>删除失败。 </div>');
            }
        });
    }

    // 模态层编辑事件
    $('#edit_btn').click(function () {
        changeVisible();
        KindEditor.html("#information-edit", $('#information-static').html());
        $('#editDiv').show();
        $('#J_selectImage_2').show();
    });

    // 模态层保存事件
    $('#edit_submit').click(function () {
        itemEditor.sync();
        var formData = $('#form-edit').serializeObject();
        $.ajax("/product/updateProduct", {
            type: 'post',
            datatype: 'json',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (data) {
                window.location.reload();
                $('#myAlert').alert();
            },
            error: function (data) {
                $('#alertBlock').html('<div id="myAlert" class="alert alert-warning"> <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>警告！</strong>保存失败。 </div>');
            }
        });
    });

    // 搜索事件
    $('#search-btn').click(function () {
        $.ajax("/product/getProductByPname", {
            type: 'get',
            data: 'pname=' + $('#search-edit').val(),
            success: function (data) {
                console.log(data);
            }
        });
    });

    // 图片上传
    KindEditor.ready(function (K) {
        var editor = K.editor({
            filePostName: "file",//form 名称
            uploadJson: '/file/upload',//上传地址
        });
        K('#J_selectImage_2').click(function () {
            editor.loadPlugin('multiimage', function () {
                editor.plugin.multiImageDialog({
                    clickFn: function (urlList) {
                        console.info("urlList:");
                        console.info(urlList);
                        var div = K('#J_imageView_2');
                        div.html('');
                        K.each(urlList, function (i, data) {
                            console.info(data);
                            div.append('<img style="width: 150px;height: 150px" src="' + data.url + '">');
                            if (i == 0) {
                                $('#imageurl_2').val(data.url);
                            }
                        });
                        editor.hideDialog();
                    }
                });
            });
        });
    });


</script>

<!--添加相关-->
<script type="text/javascript">
    var itemAddEditor;
    //页面初始化完毕后执行此方法
    $(function () {
        //创建富文本编辑器
        itemAddEditor = KindEditor.create("#form-add [name=information]", {
            resizeType: 1,
            allowImageUpload: true,
            allowFileManager: true,
            minWidth: '450px',
            // uploadJson : '/pic/upload',//服务器端提交的地址
            // filePostName:'uploadFile',//服务器端提交的文件名称
            afterUpload: function (url, data, name) {
                this.sync();//同步将富文本框中的内容同步到textarea
            }
        });
    });

    // 点击添加按钮跳出模态层
    $('#add').click(function () {
        $('#category-add').html("");
        $.ajax('/categery/getCategeryList', {
            type: 'get',
            success: function (data) {
                $.each(data.rows, function (i, temp) {
                    $('#category-add').append('<option value="' + temp.cid + '">' + temp.cname + '</option>')
                })
            }
        });
        $('#addModel').modal();
    });

    // 数据库添加按钮事件
    $('#add_submit').click(function () {
        itemAddEditor.sync();//同步富文本编辑框内容到textarea
        var formData = $('#form-add').serializeObject();
        $.ajax("/product/addProduct", {
            type: 'post',
            datatype: 'json',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            success: function (data) {
                window.location.reload();
                $('#myAlert3').alert();
            },
            error: function (data) {
                $('#alertBlock3').html('<div id="myAlert3" class="alert alert-warning"> <a href="#" class="close" data-dismiss="alert">&times;</a> <strong>警告！</strong>添加失败。 </div>');
            }
        });
    });

    // 图片上传
    KindEditor.ready(function (K) {
        var editor = K.editor({
            filePostName: "file",//form 名称
            uploadJson: '/file/upload',//上传地址
        });
        K('#J_selectImage').click(function () {
            editor.loadPlugin('multiimage', function () {
                editor.plugin.multiImageDialog({
                    clickFn: function (urlList) {
                        console.info("urlList:");
                        console.info(urlList);
                        var div = K('#J_imageView');
                        div.html('');
                        K.each(urlList, function (i, data) {
                            console.info(data);
                            div.append('<img style="width: 150px;height: 150px" src="' + data.url + '">');
                            if (i == 0) {
                                $('#imageurl').val(data.url);
                            }
                        });
                        editor.hideDialog();
                    }
                });
            });
        });
    });

</script>


</body>

</html>

